package com.huike.web.controller.common;

import com.huike.common.core.domain.AjaxResult;
import com.huike.common.utils.uuid.UUID;
import com.huike.common.utils.uuid.UUIDUtils;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${minio.endpoint}:${minio.port}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;


    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        try {

            //minion创建
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint("http://"+ENDPOINT)
                            .credentials(ACCESS_KEY, SECRET_KEY)
                            .build();
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
            } else {
                System.out.println(BUCKET_NAME+"已存在");
            }

            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //得到后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = UUID.randomUUID().toString() + suffix;
            String objectName = sdf.format(new Date()) + "/" + fileName;

            PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(BUCKET_NAME)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1).build();

            minioClient.putObject(putObjectArgs);
            AjaxResult success = AjaxResult.success();
            success.put("fileName",ENDPOINT+"/"+BUCKET_NAME+"/"+objectName);
            success.put("url",ENDPOINT+"/"+BUCKET_NAME+"/"+fileName);


            return success;


        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());

        }





    }
}
